import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { Search24 as SearchIcon } from '@carbon/icons-react';
import Button from '@kuiper-components/button';
import Input from '@kuiper-components/input';
import s from './HostSearchInput.module.css';

export default function HostSearchInput({
	className,
	value,
	onChange,
	placeholder,
}) {
	const [targetSearch, changeSearch] = React.useState(value);
	React.useMemo(() => {
		changeSearch(value);
	}, [value]);

	const handleChange = val => {
		if (!val) {
			// 清除输入的值
			onChange(undefined);
		}

		changeSearch(val);
	};
	const callOnChange = () => onChange(targetSearch);

	return (
		<Input
			className={cn(className, s.hostSearchInput)}
			placeholder={placeholder}
			after={
				<Button link primary onClick={callOnChange}>
					<SearchIcon className={s.searchIcon} />
				</Button>
			}
			type="search"
			value={targetSearch}
			onChange={handleChange}
			onPressEnter={callOnChange}
		/>
	);
}

HostSearchInput.propTypes = {
	className: PropTypes.string,
	value: PropTypes.string,
	placeholder: PropTypes.string,
	onChange: PropTypes.func,
};

HostSearchInput.defaultProps = {
	className: s.hostSearchInput,
	value: '',
	placeholder: '搜索告警资产',
	onChange: () => {},
};
